package dawn.jxufe.community.controller;

import dawn.jxufe.community.annotation.LoginRequired;
import dawn.jxufe.community.entity.Comment;
import dawn.jxufe.community.entity.DiscussPost;
import dawn.jxufe.community.entity.Event;
import dawn.jxufe.community.entity.User;
import dawn.jxufe.community.event.EventProducer;
import dawn.jxufe.community.service.LikeService;
import dawn.jxufe.community.util.CommunityConstant;
import dawn.jxufe.community.util.CommunityUtil;
import dawn.jxufe.community.util.HostHolder;
import dawn.jxufe.community.util.RedisKeyUtil;
import org.apache.http.client.RedirectStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dawn21
 * @version 1.0
 * @date 2022/8/7 16:25
 * @component
 */
@Controller
public class LikeController implements CommunityConstant {

    @Autowired
    private LikeService likeService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    // 处理异步请求的方法。
    @RequestMapping(path = "/like", method = RequestMethod.POST)
    @ResponseBody
    public String like(int entityType, int entityId, int entityUserId, int postId) {
        User user = hostHolder.getUser();
        likeService.like(user.getId(), entityType, entityId, entityUserId); // 点赞
        long likeCount = likeService.findEntityLikeCount(entityType, entityId); // 点赞数量。
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);// 状态

        Map<String, Object> map = new HashMap<>(); // // 封装返回的结果。
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);

        // 触发点赞事件。
        if (likeStatus == 1) { // 是点赞才通知。
            Event event = new Event()
                    .setTopic(TOPIC_LIKE)
                    .setUserId(hostHolder.getUser().getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserId)
                    .setData("postId", postId);
            // 使用生产者发布消息。
            eventProducer.fireEvent(event);
        }

        // 对帖子点赞再加分。
        if (entityType == ENTITY_TYPE_POST) {
            // 计算帖子的分数。不是立即算，而是将帖子放到redis中。
            String redisKey = RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(redisKey, postId);
        }

        return CommunityUtil.getJSONString(0, null, map); // 正确返回0。
    }

}
